package com.ittx.dzt.weidian.service;

import com.ittx.dzt.edi.dto.PlatformApiParamDTO;
import com.ittx.dzt.edi.dto.SkuQueryDTO;
import com.ittx.dzt.edi.dto.StoreConfigDTO;
import com.ittx.dzt.sys.response.Result;
import com.ittx.dzt.weidian.handler.AbstractBaseWeidianApiHandler;
import lombok.extern.slf4j.Slf4j;
import open.constant.PlatformApiConstant;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * cy.sku.download.bySpuID
 * 获取单个商品(vdian.item.get)
 * https://open.weidian.com/#/api/117
 * </p>
 *
 * @author wl_code@163.com
 * @version 1.0
 * @date 2025/4/1
 */
@Slf4j
@Service
public class WeidianSkuDownloadBySpuIdService extends AbstractBaseWeidianApiHandler<SkuQueryDTO> {

	@Override
	public String getLocalApiMethod() {
		return PlatformApiConstant.InboundInterface.SKU_DOWNLOAD_BY_PLATFORMSKUID;
	}

	@Override
	public Result<?> doProcess(PlatformApiParamDTO platformApiParamDTO, SkuQueryDTO skuQueryDTO) {

		List<Object> list = new ArrayList<>();
		for (String spuId : skuQueryDTO.getPlatformSpuId().split(",")) {
			// 请求接口
			Result<?> result = this.getProductById(spuId, platformApiParamDTO);
			if (!result.isSuccess()) {
				return result;
			}
			Object resultData = result.getData();
			// 同步返回
			if (skuQueryDTO.getIsAsync() == 0) {
				list.add(resultData);
			} else {
				platformApiParamDTO.setPlatformIdentifierTag(spuId);
				result = this.sendRequestToPlatform(platformApiParamDTO, resultData, true);
				if (result.hasError()) {
					return result;
				}
			}
		}
		// 同步返回
		if (skuQueryDTO.getIsAsync() == 0) {
			return Result.success().addData(list).addMsg(platformApiParamDTO.getStoreConfig().getChainUniqueCode());
		}
		return Result.success();
	}

	/**
	 * 根据id获取商品
	 *
	 * @param id
	 * @param platformApiParamDTO
	 * @return
	 */
	public Result<?> getProductById(String id, PlatformApiParamDTO platformApiParamDTO) {
		StoreConfigDTO storeConfig = platformApiParamDTO.getStoreConfig();
		return this.getProductBySdk(id, platformApiParamDTO);
	}

	/**
	 * sdk获取商品
	 *
	 * @param productId 商品id
	 */
	public Result<?> getProductBySdk(String productId, PlatformApiParamDTO platformApiParamDTO) {
		Map<String, Object> params = new HashMap<>();
		StoreConfigDTO storeConfig = platformApiParamDTO.getStoreConfig();
		String requestId = platformApiParamDTO.getRequestId();
		// 商品Id
		params.put("itemid", productId);
		Result<?> result = this.executeWeidianApi(storeConfig, params, requestId);
		if (!result.isSuccess()) {
			return result;
		}
		Map<String, Object> resultMap = (Map<String, Object>) result.getData();
		return Result.success().addData(resultMap.get("result"));

	}

	@Override
	public String getWeidianMethod() {
		return "vdian.item.get";
	}

	@Override
	public String getWeidianApiVersion() {
		return "1.0";
	}

	@Override
	public String getWeidianApiFormat() {
		return null;
	}
}
